package com.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.reggie.common.R;
import com.reggie.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //定义一个路径匹配器，包含通配符
    public static final  AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest servletRequest= (HttpServletRequest) request;
        HttpServletResponse servletResponse= (HttpServletResponse) response;


        //1.获取请求的路径，判断是否继续处理
        String requestURI = servletRequest.getRequestURI();

        //不被处理的请求,登录请求、退出请求、静态的资源
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/front/login",
                "/user/sendMsg",
                "/user/login"
        };

        if (checkURI(urls,requestURI)) {
            //匹配成功放行
            chain.doFilter(servletRequest,servletResponse);
            return;
        }

        //2.后台登陆需要处理的路径

        if (servletRequest.getSession().getAttribute("employee")!=null){

            //获取当前的对象信息用于公共数据的赋值
            long id = Thread.currentThread().getId();
            log.info("当前线程的id"+id);
            ThreadLocalUtil.setId((Long) servletRequest.getSession().getAttribute("employee"));
            //已经登录的用户直接放行
            chain.doFilter(servletRequest,servletResponse);

            return;
        }
        //移动端用户登录的处理的路径
        if (servletRequest.getSession().getAttribute("user")!=null){

            //获取当前的对象信息用于公共数据的赋值
            long id = Thread.currentThread().getId();
            log.info("当前线程的id"+id);
            ThreadLocalUtil.setId((Long) servletRequest.getSession().getAttribute("user"));
            //已经登录的用户直接放行
            chain.doFilter(servletRequest,servletResponse);

            return;
        }
        //3.没有登录的用户前端做了响应拦截器（request.js），方法没有返回值需要通过json的方式给客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }
    /**
     * 路径的验证，如果不属于处理的路径则返回true，否则返回false
     *
     * @param urls 匹配的模式
     * @param requestURI 匹配的路径
     * */
    public boolean checkURI(String[] urls ,String requestURI){
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)) {
                //匹配成功
                return true;
            }
        }

        return false;
    }
}
